<template>
  <div class="outbound-task-main">
    <Dialog :appDialog="appDialog">
      <div class="content">
        <el-scrollbar height="450px">
          <el-form 
            ref="formRef" 
            :model="formData" 
            :rules="rules"
            label-width="130px">
            <el-form-item label="有效手机号数量：" prop="phone_num">
              <div class="phone-num">{{ formData.phone_num }}</div>
            </el-form-item>
            <div class="tips">
              <span>注意：</span>为了保证外呼质量，建议一个外呼任务建议有效手机号数量不要超过20w条。如果超过，建议分成多个人群包来创建外呼任务。
            </div>
            <el-form-item label="外呼任务标题：" prop="name">
              <el-input 
                class="form-input" 
                v-model="formData.name" 
                placeholder="请输入外呼任务标题" 
                size="small">
              </el-input>
            </el-form-item>
            <el-form-item label="选择话术分组：" prop="destination_extension">
              <el-cascader 
                v-model="formData.destination_extension"
                :props="props"
                :options="formData.wordsGroup" 
                :show-all-levels="false"
                clearable
                placeholder="请选择话术分组"
                size="small"  />
            </el-form-item>
            <el-form-item label="选择呼叫时间：" prop="dial_time_id">
              <el-select 
                v-model="formData.dial_time_id" 
                filterable
                clearable
                placeholder="请选择呼叫时间" 
                size="small">
                <el-option
                  v-for="item in formData.timeGroup"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择线路：" prop="caller_line_id">
              <el-select 
                v-model="formData.caller_line_id" 
                filterable
                clearable
                placeholder="请选择线路" 
                size="small">
                <el-option
                  v-for="item in formData.callerLineList"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择重呼规则：" prop="auto_recycle_rule_id">
              <el-select 
                v-model="formData.auto_recycle_rule_id" 
                filterable
                clearable
                placeholder="请选择重呼规则" 
                size="small">
                <el-option
                  v-for="item in formData.auto_recycle_rules"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择并发数：" prop="maximumcall">
              <el-input
                class="form-input" 
                v-model="formData.maximumcall" 
                placeholder="请输入并发数" 
                size="small">
              </el-input>  
            </el-form-item>
            <el-form-item label="挂机短信：" prop="is_hangup_sms">
              <el-switch v-model="formData.is_hangup_sms" :active-value="2" :inactive-value="1" />
              <div v-if="formData.is_hangup_sms == 2">
                <div class="hang-up-sms-item" v-for="(item,index) in formData.smsList" :key="index">
                  <div class="hang-up-sms-item-title">
                    <div>触达{{index+1}}：</div>
                    <img v-if="index" @click="handlerSmsDel(index)" src="/static/delete.png" alt="">
                  </div>
                  <el-form 
                    ref="formRef2" 
                    :model="item" 
                    :rules="rules"
                    label-width="100px">
                    <el-form-item label="意向标签：" prop="con">
                      <el-cascader 
                        v-model="item.tag_ids"
                        :props="labelProps"
                        :options="item.labelList" 
                        :show-all-levels="false"
                        @visible-change="visibleChangeLabel($event, index)"
                        clearable
                        placeholder="请选择意向标签"
                        size="small"  />
                    </el-form-item>
                    <el-form-item label="短信配置：" class="hang-up-sms-item-config">
                      <el-select 
                        v-model="item.sms_sign"
                        @change="changeSmsSign($event,index)"
                        placeholder="请选择短信签名" 
                        size="small">
                        <el-option
                          v-for="item in formData.smsSignList"
                          :key="item.id"
                          :label="item.sign_name"
                          :value="item.id"
                        />
                      </el-select>
                      <el-select 
                        v-model="item.sms_template"
                        placeholder="请选择短信模板" 
                        size="small">
                        <el-option
                          v-for="el in item.smsTemplateList"
                          :key="el.id"
                          :label="el.template_name"
                          :value="el.id"
                        />
                      </el-select>
                      <div class="hang-up-sms-item-desc" v-if="item.sms_sign || item.sms_template">
                        【{{ getSmsTemplate('1', item.sms_sign, index) }}】{{ getSmsTemplate('2', item.sms_template, index) }}
                      </div>
                    </el-form-item>
                  </el-form>
                </div>
                <el-button @click="handlerSms" :disabled="disabledSms">添加短信触达</el-button>
              </div>
            </el-form-item>
          </el-form>
        </el-scrollbar>
      </div>
    </Dialog>
    <Dialog :appDialog="loadingInfo" @close="closeProgressDialog">
      <div class="loading-content">
        <div class="loading-title">{{ formData.processText }}</div>
        <div class="loading-number">{{ formData.process_number_qty }}/{{ formData.total_number_qty }}</div>
        <el-progress 
          class="loading-progress" 
          :text-inside="true" 
          :stroke-width="26" 
          :percentage="formData.progress" />
      </div>
    </Dialog>
    <!-- <BatchLabel ref="batchLabelRef" @save="getTagsFun" /> -->
  </div>
</template>
<script setup lang="ts">
import { ref, reactive, watch, computed, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getCustomeSmsSignList, getCustomeSmsTemplateList } from '@/api/customer/manage/list'
import { listGroupType, listTag, listgroupTag, grouplist } from '@/api/customerCenter'
import { getCall } from '@/api/channel/index'
import Dialog from '@/components/Dialog.vue'
import BatchLabel from '@/components/BatchLabel.vue'
import { 
  createAiTask,
  getCalltimeGroup, 
  getWordsGroup,
  getCallerLine,
  getAiJobProcess,
  getAiTaskInit
} from '@/api/customer/crowdManage/index'

const props = {
  label: 'name',
  value: 'id',
  children: 'caller_lines'
}

const labelProps = {
  multiple: true,
  emitPath: false,
  label: 'name',
  value: 'id',
  children: 'tags'
}

const formRef = ref<any>(null)
const batchLabelRef = ref<any>(null)


const formData = reactive<any>({
  name: '',
  destination_extension: '',
  maximumcall: '',
  caller_line_id: '',
  dial_time_id: '',
  auto_recycle_rule_id: '',
  crowd_package_id: '',
  max_recycle_limit: 0,
  is_hangup_sms: 1,
  smsList: [
    {
      tag_ids: [],
      sms_sign: '',
      sms_template: '',
      smsTemplateList: [],
      labelList: []
    }
  ],
  wordsGroup: [],
  timeGroup: [],
  callerLineList: [],
  auto_recycle_rules: [],
  smsSignList: [],
  smsTemplateList: [],
  sign_id: '',
  labelList: [],
  progress: 0,
  process_number_qty: 0,
  total_number_qty: 0,
  processText: '任务开始',
  timer: ''
})

const validateNum = (rule: any, value: any, callback: any) => {
  let flag = value && /(^[1-9]\d*$)/.test(value)
  if(flag) {
    callback();
  } else {
    callback(new Error('请输入正确并发数'));
  }
};
const rules = reactive<any>({
  name: [{ required: true, message: '请输入人群包名称', trigger: 'blur' }],
  destination_extension: [{ required: true, message: '请选择话术分组' }],
  dial_time_id: [{ required: true, message: '请选择呼叫时间' }],
  caller_line_id: [{ required: true, message: '请选择线路' }],
  auto_recycle_rule_id: [{ required: true, message: '请选择重呼规则' }],
  maximumcall: [{ required: true, validator: validateNum, trigger: 'blur' }],
})

const cancelHandel = () => {
  appDialog.visible = false
}

const submitHandel = async () => {
  formRef.value.validate(async (res: any) => {
    if(res) {
      let { 
        caller_line_id,
        auto_recycle_rule_id,
        maximumcall, 
        name, 
        dial_time_id,
        crowd_package_id,
        is_hangup_sms
      } = formData
      let touch_list: any = []
      if(is_hangup_sms == 2) {

        for(let i = 0;i < formData.smsList.length;i++) {
          let obj = formData.smsList[i]
          if(!obj.tag_ids.length) {
            ElMessage.error(`触达${i+1},请选择意向标签`)
            return
          }else if(!obj.sms_sign) {
            ElMessage.error(`触达${i+1},请选择短信签名`)
            return
          }else if(!obj.sms_template) {
            ElMessage.error(`触达${i+1},请选择短信模板`)
            return
          }
          touch_list.push({
            // tag_ids: el.tag_ids.map((i: any) => i[1]),
            tag_ids: obj.tag_ids,
            sms_sign: obj.sms_sign,
            sms_template: obj.sms_template
          })
        }
        
        // formData.smsList.map((el: any,idx: number) => {
        //   touch_list.push({
        //     // tag_ids: el.tag_ids.map((i: any) => i[1]),
        //     tag_ids: el.tag_ids,
        //     sms_sign: el.sms_sign,
        //     sms_template: el.sms_template
        //   })
        // })
      }
      let params = {
        caller_line_id, //外呼线路ID
        destination_extension: formData.destination_extension[0], //话术分组ID
        auto_recycle_rule_id,
        maximumcall, //最大并发数
        name, //外呼任务名称
        dial_time_id, //呼叫时间组ID
        crowd_package_id, //人群包ID
        is_hangup_sms, 
        touch_list
      }
      let res = await createAiTask(params)
      formData.ai_async_job_id = res.ai_async_job_id
      appDialog.visible = false
      loadingInfo.visible = true
      formData.progress = 0
      formData.process_number_qty = 0
      formData.total_number_qty = 0
      getJobsProgress()
    }
  })
  // ElMessage.success('')


}

const appDialog = reactive<any>({
  visible: false,
  title: '【人群包名称】-- 创建外呼任务',
  width: '38%',
  cancel: cancelHandel,
  submit: submitHandel,
  cancelText: '取消',
  submitText: '开始生成'
})

const loadingInfo = reactive<any>({
  visible: false,
  width: '50%',
})

const visibleChangeWords = async () => {
  if(!formData.wordsGroup.length) {
    let params = {
      page: 1, page_size: 99999
    }
    let res = await getWordsGroup(params)
    formData.wordsGroup = res.data || []
  }
}

const visibleChangeCaller = async () => {
  if(!formData.callerLineList.length) {
    let params = {
      page: 1, page_size: 99999
    }
    let res = await getCallerLine(params)
    formData.callerLineList = res.data || []
  }
}

const visibleChangeSmsSign = async () => {
  let params = {
    sign_name: '',
    state: 2
  }
  let res = await getCustomeSmsSignList(params)
  formData.smsSignList = res.result || []
}

const visibleChangeSmsTemp = async (val: any, index: number) => {
  formData.smsList[index].sms_template = ''
  let parmas = {
    sign_id: val,
    state: 2,
    page: 1,
    page_size: 1000
  }
  let res = await getCustomeSmsTemplateList(parmas)
  formData.smsList[index].smsTemplateList = res.data || []

}

const changeSmsSign = (val: any, index: number) => {
  visibleChangeSmsTemp(val, index)

}

const getTagsFun = (val: any) => {
}

const handlerLabel = () => {
  batchLabelRef.value.hasConditiion = false
  batchLabelRef.value.dialogData.labelChooseType = 2
  // batchLabelRef.value.chooseDataArr = [...formData.tagList]
  batchLabelRef.value.dialogVisible = true
}

const handlerSms = () => {
  formData.smsList.push({
    tag_ids: [],
    sms_sign: '',
    sms_template: '',
    smsTemplateList: [],
    labelList: formData.labelList
  })
}

const handlerSmsDel = (index: number) => {
  formData.smsList.splice(index,1)
}

// 处理意向标签不能重复
const visibleChangeLabel = (val: boolean, index: number) => {
  if(!val) return
  let list: any = []
  list = formData.smsList.map((el: any, idx: number) => {
    if(index != idx) {
      return el && el.tag_ids.filter((i: any) => i)
    }
  })
  list = list.flat()
  formData.smsList[index].labelList.map((el: any) => {
    el && el.tags.map((i: any) => {
      if(list.some((j: any) => j == i.id)) {
        i.disabled = true
      }else {
        i.disabled = false
      }
    })
    if(el.tags.every((i: any) => i.disabled)) {
      el.disabled = true
    }else {
      el.disabled = false
    }
  })
}

const closeProgressDialog = () => {
  clearTimeout(formData.timer)
}

const getJobsProgress = async () => {
  let params = {
    ai_async_job_id: formData.ai_async_job_id
  }
  let res = await getAiJobProcess(params)
  formData.process_number_qty = res.process_number_qty
  formData.total_number_qty = res.total_number_qty
  formData.progress = parseInt((res.process_number_qty/res.total_number_qty)*100)
  if(formData.process_number_qty != formData.total_number_qty) {
    formData.processText = '人群包上传中...'
    formData.timer = setTimeout(() => {
      getJobsProgress()
    }, 1000);
  }else {
    setTimeout(() => {
      formData.processText = '任务完成'
      loadingInfo.visible = false
      getCall({module: 2}).then((r: any) => {
        window.open(r.sso_url)
      })
    },1000)
  }
}

const getSmsTemplate = (type: string,id: number|string, index: number) => {
  if(type == '1') {
    let info = formData.smsSignList.find((el: any) => el.id == id) || {}
    return info.sign_name
  }else if(type == '2') {
    let info = formData.smsList[index]?.smsTemplateList.find((el: any) => el.id == id) || {}
    return info.template_content
  }
}

const initLabel = async () => {
  let res = await listGroupType({create_type: 4})
  if(res && !res.length) return
  let params = {
    keyword: '',
    type_list: res[0]?.id,
    page: 1,
    page_size: 50,
  }
  let res2 = await listTag(params)
  let list = res2.data || []
  list.forEach((el: any) => {
    el.id = el.group_type_value
    el.name = el.group_name
    if(el.tags && !el.tags.length) {
      el.disabled = true
    }
  })
  formData.labelList = list
  formData.smsList[0].labelList = list

}

const initData = async () => {
  let res = await getAiTaskInit({})
  formData.wordsGroup = res.outbound_group || []
  formData.timeGroup = res.enum_dial_time_group || []
  formData.callerLineList = res.caller_line_list || []
  formData.auto_recycle_rules = res.auto_recycle_rules || []
  formData.max_recycle_limit = res.max_recycle_limit
}

const disabledSms = computed(() => {
  let flag = false
  let list = formData.smsList.map((el: any, idx: number) => {
    return el && el.tag_ids.filter((i: any) => i)
  })
  list = list.flat()
  let ary = formData.labelList.map((el: any) => {
    return el && el.tags.filter((i: any) => i.id)
  })
  ary = ary.flat()
  if(list.length && list.length == ary.length) {
    flag = true
  }
  return flag
})

onMounted(() => {
  initData()
  initLabel()
  visibleChangeSmsSign()
})

onUnmounted(() => {
  clearTimeout(formData.timer)
})

defineExpose({
  appDialog,
  formData
})

</script>
<style lang="scss" scoped>
.outbound-task-main {
  .content {
    .tips {
      margin-top: -8px;
      padding: 0 5px 20px;
      font-size: 14px;
      line-height: 20px;
      span {
        color: #ff6b00;
      }
    }
    .form-input {
      max-width: 215px;
    }
    .hang-up-sms-item {
      margin-bottom: 20px;
      padding: 0 16px;
      background: rgb(239, 239, 239);
      border-radius: 4px;
      .hang-up-sms-item-title {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .hang-up-sms-item-config {
        max-width: 315px;
      }
      .hang-up-sms-item-desc {
        margin-bottom: 12px;
        padding: 2px 0;
        line-height: 20px;
        border-radius: 2px;
        font-size: 12px;
        background: rgba(80, 135, 236, 0.2);
      }
    }
  }
  .loading-content {
    padding-top: 20px;
    height: 160px;
    text-align: center;
    .loading-number {
      padding: 10px 0;
    }
    .loading-progress {
      margin: 10px 10px;
    }
  }
}
</style>